package com.greenyoung.pwiki.markdown.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.greenyoung.pwiki.markdown.entity.Markdown;
import com.greenyoung.pwiki.markdown.mapper.MarkdownMapper;
import com.greenyoung.pwiki.markdown.service.MarkdownService;
import com.greenyoung.pwiki.markdown.utils.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.Timestamp;

@Service
public class MarkdownServiceImpl implements MarkdownService {
    @Autowired
    MarkdownMapper markdownMapper;

    /**
     * 先存储文件，再将文件相关信息写入数据库
     *
     * @param multipartFile
     * @throws Exception
     */
    @Override
    public void saveFile(MultipartFile multipartFile) throws Exception {
        Markdown markdown = new Markdown();
        long id = IdUtil.nextId();
        markdown.setId(id);
        markdown.setName(multipartFile.getOriginalFilename());
        markdown.setCreateTime(new Timestamp(System.currentTimeMillis()));
        //TODO: 设置分布式文件路径
        String dirPath = ResourceUtils.getURL("classpath:").getPath();
        String filePath = dirPath + "/com/greenyoung/pwiki/markdown/" + id + ".md";
        File savedFile = new File(filePath);
        if (!savedFile.exists()) {
            savedFile.mkdirs();
        }
        markdown.setPath(filePath);
        multipartFile.transferTo(savedFile);
        markdownMapper.insertSelective(markdown);
        //TODO:先返回客户端数据，再使用消息队列处理文件的标题
    }

    @Override
    public PageInfo getMarkdownsByPageNum(Integer pageNum, Integer pageSize) throws Exception {
        return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> markdownMapper.selectAll());
    }

    @Override
    public String getMarkdownContentById(Long id) throws Exception{
        Markdown markdown=markdownMapper.selectByPrimaryKey(id);
        return getMarkdownContentByPath(markdown.getPath());
    }

    String getMarkdownContentByPath(String filePath) throws Exception {
        //TODO:解决大文件读取问题
        File file = new File(filePath);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        //5M cache
        BufferedReader reader = new BufferedReader(new InputStreamReader(bis, "utf-8"), 5 * 1024 * 1024);
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n\r");
        }
        return sb.toString();
    }
}
